import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import BabelConfig_vite from "../../babel.config_vite";
import compilerAll from "@vue/compiler-sfc";
import babel from "@babel/core";

function getVueCompiler() {
  const babelConfig = BabelConfig_vite()
  let oldCompileScript = compilerAll.compileScript
  compilerAll.compileScript = (sfc, options) => {
    let value = oldCompileScript(sfc, options)
    if (value && value.content) {
      let filename = `${sfc.filename}?lang=.${value.lang}`
      const babelResult = babel.transformSync(value.content, {
        filename,
        ...babelConfig,
        sourceMaps: !options.isProd,
        // @ts-ignore
        inputSourceMap: value.map,
        sourceFileName: sfc.filename,
        sourceType: 'module',
        sourceRoot: value.map?.sourceRoot
      })
      if (value.map && babelResult.map) {
        // @ts-ignore
        value.map = {
          ...value.map,
          ...babelResult.map
        }
      }
      value.content = babelResult.code
    }
    return value
  }
  return compilerAll
}

export function vitePluginVue3Babel() {
  return [
    vue({
      compiler: getVueCompiler()
    }),
    // vue(),
    vueJsx(),
  ]
}

/**
 *     "@babel/core": "^7.24.9",
 *     "@babel/plugin-proposal-class-properties": "^7.18.6",
 *     "@babel/plugin-proposal-decorators": "^7.24.7",
 *     "@babel/plugin-proposal-private-methods": "^7.18.6",
 *     "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
 *     "@babel/plugin-transform-private-methods": "^7.24.7",
 *     "@babel/preset-env": "^7.24.8",
 *     "@babel/preset-typescript": "^7.24.7",
 *     "@types/babel__core": "^7.20.5",
 *         "@vitejs/plugin-vue": "5.0.4",
 *     "@vitejs/plugin-vue-jsx": "3.1.0",
 */
